package rpc_netty.server.ServiceProvider;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rpc_1.Service.RpcException;
import rpc_1.interfaces.ServiceProvider;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

//将服务注册分离出来
//这个类，做为一个容器，保存注册过的服务
public class DefaultServiceProvider implements ServiceProvider {
    private static final Logger logger= LoggerFactory.getLogger(DefaultServiceProvider.class);

    //key代表接口名，value代表实现该接口的serviceImpl
    private static final Map<String,Object> serviceMap=new ConcurrentHashMap<>();
    private static final Set<String> registerService=ConcurrentHashMap.newKeySet();

    /*
    register to the container
     */
    @Override
    public synchronized <T> void provide(T service) throws RpcException {
        String serviceName=service.getClass().getCanonicalName();
        if (registerService.contains(serviceName)) return;
        registerService.add(serviceName);
        Class<?>[] interfaces = service.getClass().getInterfaces();
        if (interfaces.length==0)
            throw new RpcException("Rpc service implements none interfaces!");
        //遍历该serviceImpl实现的接口，对应它实现了哪些功能（interfaces），加入到map集合中
        for (Class<?> anInterface : interfaces) {
            serviceMap.put(anInterface.getCanonicalName(),service);
        }
        logger.info("register service {} to the interfaces {} succeed",serviceName,interfaces);
    }

    @Override
    public synchronized Object getService(String serviceName) throws RpcException {
        Object service=serviceMap.get(serviceName);
        if (service==null)
            throw new RpcException("Rpc service not found");
        return service;

    }
}
